package com.zy.openchat.core.manager;

import com.zy.openchat.App;
import com.zy.openchat.core.model.file.FileTaskInfo;
import com.zy.openchat.core.model.message.ChatInfo;
import com.zy.openchat.core.model.user.UserInfo;
import com.zy.openchat.util.Common;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

public class TgData {
    //以下均为共享数据，需要做线程读写同步控制
    //共享数据读写锁
    private ReadWriteLock readWriteLock = new ReentrantReadWriteLock();
    //td对象
    private long tdClient = 0;
    //请求序列
    private int requestId = 1;
    //任务列表
    private Map<Integer, TgTask> requestQueue = new HashMap<>();
    //用户状态
    private TelegramManager.GoUserState userState = TelegramManager.GoUserState.GoUserState_Unkown;
    //连接状态
    private TelegramManager.GoUserConnectionState userConnectionState = TelegramManager.GoUserConnectionState.GoUserConnectionState_Connecting;
    //当前正在聊天的chatid - 0表示没有
    private long curChatId;
    //核心列表
    //最近会话
    private Map<Long, ChatInfo> chat_dic = new HashMap<>();
    //联系人资料
    private Map<Long, UserInfo> contacts_dic = new HashMap<>();
    //文件下载队列
    private Map<String, FileTaskInfo> fileTask_dic = new HashMap<>();

    private List<Long> notMemberSuperGroupId_dic = new ArrayList<>();

    private Map<String,String> groupNickName_dic = new HashMap<>();

    private Map<Long,String> userRealNames = new HashMap<>();

    public void putUserRealyNames(long userId,String nickName){
        userRealNames.put(userId,nickName);
    }
    public String getUserRealyName(long userId){
        if(userRealNames.containsKey(userId)){
            return userRealNames.get(userId);
        }
        return null;
    }


    private String groupNickNameKey(long chatId,long userId){
        return String.format("%s-%s",String.valueOf(chatId),String.valueOf(userId));
    }

    public void putGroupNickNames(long chatId,long userId,String nickName){
        groupNickName_dic.put(groupNickNameKey(chatId,userId),nickName);
    }


    public String getGroupNickName(long chatId,long userId){
        String key = groupNickNameKey(chatId,userId);
        if(!groupNickName_dic.containsKey(key)){
            TelegramManager.getTelegramManager().getGroupMember(App.getInstanse(),chatId,userId,null);
        }
        return groupNickName_dic.get(key);
    }



    //危险-外部不要调用
    public long getTdClient() {
        long client = 0;
        readWriteLock.readLock().lock();
        client = tdClient;
        readWriteLock.readLock().unlock();
        return client;
    }

    //危险-外部不要调用
    public void setTdClient(long client) {
        readWriteLock.writeLock().lock();
        this.tdClient = client;
        readWriteLock.writeLock().unlock();
    }

    //危险-外部不要调用
    public boolean isValid() {
        long client = getTdClient();
        return client != 0;
    }

    //危险-外部不要调用
    public int getNextRequestId() {
        int id = 0;
        readWriteLock.writeLock().lock();
        id = requestId;
        requestId++;
        readWriteLock.writeLock().unlock();
        return id;
    }

    //危险-外部不要调用
    public TgTask getTgTask(int rtId) {
        TgTask tg = null;
        readWriteLock.readLock().lock();
        tg = requestQueue.get(rtId);
        readWriteLock.readLock().unlock();
        return tg;
    }

    //危险-外部不要调用
    public void addTgTask(TgTask tg) {
        if (tg != null) {
            readWriteLock.writeLock().lock();
            requestQueue.put(tg.rtId, tg);
            readWriteLock.writeLock().unlock();
        }
    }

    //危险-外部不要调用
    public void removeTgTask(int rtId) {
        readWriteLock.writeLock().lock();
        requestQueue.remove(rtId);
        readWriteLock.writeLock().unlock();
    }

    //获取当前用户状态
    public TelegramManager.GoUserState getUserState() {
        TelegramManager.GoUserState state;
        readWriteLock.readLock().lock();
        state = userState;
        readWriteLock.readLock().unlock();
        return state;
    }

    //危险-外部不要调用
    public void setUserState(TelegramManager.GoUserState state) {
        readWriteLock.writeLock().lock();
        this.userState = state;
        readWriteLock.writeLock().unlock();
    }

    //获取当前用户连接状态
    public TelegramManager.GoUserConnectionState getUserConnectionState() {
        TelegramManager.GoUserConnectionState state;
        readWriteLock.readLock().lock();
        state = userConnectionState;
        readWriteLock.readLock().unlock();
        return state;
    }

    //危险-外部不要调用
    public void setUserConnectionState(TelegramManager.GoUserConnectionState state) {
        readWriteLock.writeLock().lock();
        this.userConnectionState = state;
        readWriteLock.writeLock().unlock();
    }

    //获取当前会话
    public long getCurChatId() {
        long id;
        readWriteLock.readLock().lock();
        id = curChatId;
        readWriteLock.readLock().unlock();
        return id;
    }

    //设置当前会话
    public void setCurChatId(long id) {
        readWriteLock.writeLock().lock();
        this.curChatId = id;
        readWriteLock.writeLock().unlock();
    }

    //危险-外部不要调用
    public void addOrUpdateContact(UserInfo user) {
        if (user != null) {
            readWriteLock.writeLock().lock();
            contacts_dic.put(user.id, user);
            readWriteLock.writeLock().unlock();
        }
    }

    //查询联系人
    public UserInfo contactInfo(long userId) {
        if (userId == UserInfo.getUserInfo().id) {
            return UserInfo.getUserInfo();
        }
        UserInfo user;
        readWriteLock.readLock().lock();
        user = contacts_dic.get(userId);
        readWriteLock.readLock().unlock();
        return user;
    }

    //查询会话
    public ChatInfo chatInfo(long chatId) {
        ChatInfo chat;
        readWriteLock.readLock().lock();
        chat = chat_dic.get(chatId);
        readWriteLock.readLock().unlock();
        return chat;
    }

    //危险-外部不要调用
    public void addOrUpdateChat(ChatInfo chat) {
        if (chat != null) {
            readWriteLock.writeLock().lock();
            chat_dic.put(chat.id, chat);
            readWriteLock.writeLock().unlock();
        }
    }

    public boolean isInNotMemberSuperGroups(ChatInfo chat){
        if (chat == null) {
            return false;
        }
        if(chat.isSuperGroup()&&!Common.isEmpty(notMemberSuperGroupId_dic)&&notMemberSuperGroupId_dic.contains(chat.superGroupId())){
            return true;
        }
        return false;

    }

    public ChatInfo removeChatBySecretChatId(long secretChatId){
        ChatInfo info = null;
        readWriteLock.writeLock().lock();
        for (ChatInfo chatInfo : chat_dic.values()) {
            if(chatInfo.isSecretChat()&&chatInfo.secretChatId() == secretChatId){
                info = chatInfo;
                chat_dic.remove(chatInfo.id);
                break;
            }
        }
        readWriteLock.writeLock().unlock();
        return info;
    }

    public boolean addNotMemberSuperGroup(long supergroupId){
        boolean isHandle = false;
        readWriteLock.writeLock().lock();
        if(!notMemberSuperGroupId_dic.contains(supergroupId)){
            notMemberSuperGroupId_dic.add(supergroupId);
            isHandle = true;
        }
        readWriteLock.writeLock().unlock();
        return isHandle;
    }

    public boolean removeNotMemberSuperGroup(long supergroupId){
        boolean isHandle = false;
        readWriteLock.writeLock().lock();
        if(notMemberSuperGroupId_dic.contains(supergroupId)){
            notMemberSuperGroupId_dic.remove(supergroupId);
            isHandle = true;
        }
        readWriteLock.writeLock().unlock();
        return isHandle;
    }

    //危险-外部不要调用
    public FileTaskInfo fileTaskInfo(String taskId) {
        FileTaskInfo task;
        readWriteLock.readLock().lock();
        task = fileTask_dic.get(taskId);
        readWriteLock.readLock().unlock();
        return task;
    }

    //危险-外部不要调用
    public void addFileTask(String keyString, FileTaskInfo task) {
        if (task != null) {
            readWriteLock.writeLock().lock();
            task.timestamp = System.currentTimeMillis();
            fileTask_dic.put(keyString, task);
            readWriteLock.writeLock().unlock();
        }
    }

    //危险-外部不要调用
    public void removeFileTask(String keyString) {
        readWriteLock.writeLock().lock();
        fileTask_dic.remove(keyString);
        readWriteLock.writeLock().unlock();
    }

    //获取我的好友列表
    public List<UserInfo> getMyContacts() {
        List<UserInfo> list = new ArrayList<>();
        readWriteLock.readLock().lock();
        List<UserInfo> all = new ArrayList<>(contacts_dic.values());
        for (UserInfo user : all) {
            if (user.is_contact) {
                list.add(user);
            }
        }
        readWriteLock.readLock().unlock();
        return list;
    }

    //根据关键字获取我的好友列表
    public List<UserInfo> getMyContacts(String keyword) {
        List<UserInfo> list = new ArrayList<>();
        readWriteLock.readLock().lock();
        List<UserInfo> all = new ArrayList<>(contacts_dic.values());
        for (UserInfo user : all) {
            if (user.is_contact && user.isMatch(keyword)) {
                list.add(user);
            }
        }
        readWriteLock.readLock().unlock();
        return list;
    }

    //获取群组列表
    public List<ChatInfo> getMyGroups() {
        List<ChatInfo> list = new ArrayList<>();
        readWriteLock.readLock().lock();
        List<ChatInfo> all = new ArrayList<>(chat_dic.values());
        for (ChatInfo chat : all) {
            if (chat.isGroup()) {
                list.add(chat);
            }
        }
        readWriteLock.readLock().unlock();
        return list;
    }

    //获取群组列表
    public List<ChatInfo> getMyGroups(String keyword) {
        List<ChatInfo> list = new ArrayList<>();
        readWriteLock.readLock().lock();
        List<ChatInfo> all = new ArrayList<>(chat_dic.values());
        for (ChatInfo chat : all) {
            if (chat.isGroup() && chat.isMatch(keyword)) {
                list.add(chat);
            }
        }
        readWriteLock.readLock().unlock();
        return list;
    }

    //获取会话列表
    public List<ChatInfo> getChatList() {
        List<ChatInfo> list = null;
        readWriteLock.readLock().lock();
        list = new ArrayList<>(chat_dic.values());
        readWriteLock.readLock().unlock();
        return list;
    }

    //清理缓存
    //危险-外部不要调用
    public void cleanCache() {
        readWriteLock.writeLock().lock();
        chat_dic.clear();
        contacts_dic.clear();
        fileTask_dic.clear();
        readWriteLock.writeLock().unlock();
    }
}